package hunan.qianyuan.codefatherback.core;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import hunan.qianyuan.codefatherback.ai.model.HtmlCodeResult;
import hunan.qianyuan.codefatherback.ai.model.MultiFileCodeResult;
import hunan.qianyuan.codefatherback.ai.model.enums.CodeGenTypeEnum;
import hunan.qianyuan.codefatherback.constant.AppConstant;

import java.io.File;

public class CodeFileSaver {
    //    1.文件保存根目录
    private static final String ROOT_DIR = AppConstant.CODE_OUTPUT_ROOT_DIR;

    //    2.保存HtmlCodeResult文件
    public static File saveHtmlCodeResult(HtmlCodeResult result,Long appId) {
        String baseDirPath = buildUniquePath(CodeGenTypeEnum.HTML.getValue(),appId);
        saveFile(baseDirPath, "index.html", result.getHtmlCode());
        return new File(baseDirPath);
    }

    //    3.保存MultiFileCodeResult文件
    public static File saveMultiFileCodeResult(MultiFileCodeResult result,Long appId) {
        String baseDirPath = buildUniquePath(CodeGenTypeEnum.MULTI_FILE.getValue(),appId);
        saveFile(baseDirPath, "index.html", result.getHtmlCode());
        saveFile(baseDirPath, "style.css", result.getCssCode());
        saveFile(baseDirPath, "script.js", result.getJsCode());
        return new File(baseDirPath);
    }

    //    4.构建唯一路径使用雪花算法
    private static String buildUniquePath(String bizType,Long appId) {
        String uniquePath = StrUtil.format("{}_{}", bizType, appId);
        String path = ROOT_DIR + File.separator + uniquePath;
        FileUtil.mkdir(path);
        return path;
    }

    //    5.单个文件保存
    private static File saveFile(String filePath, String fileName, String content) {
        String fullPath = filePath + File.separator + fileName;
        return FileUtil.writeUtf8String(content, fullPath);
    }
}
